﻿package net.molchat.android.scrn;


import net.molchat.android.core.Setting;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Shader.TileMode;
import android.util.Log;


// ======================================== Графическое поле и функции рисования
public class Draw {

//==================================================================== Constants


//======================================================================= Fields

// Canvas
protected static Canvas g; // Buffer graphic field
protected static Bitmap bmp; // Bitmap for praphic buffer
public static int dispW; // Размер экрана
public static int dispH;


// Шрифты
protected static Paint fontClk; // Для часов в сообщениях (маленький)
protected static Paint fontStat; // Для строки статуса (маленький)
public static Paint fontMess; // Для сообщений (средний)
protected static Paint fontTit; // Для заголовков
public static int fontClkH = 11;
public static int fontStatH = 11;
public static int fontMessH = 12;
public static int fontTitH = 14; // Высота текстовой строки заголовков комнат

public static int fontClkGap = fontClkH >> 2;
public static int fontMessGap = fontMessH >> 2;

public static int timeMessW, timeStatW; // Ширина поля часов
public static int timeMessOff; // Ширина отступа от поля часов

// Масштабные коэффициенты толщины линий
protected static int fact = 1;
protected static int fact2 = fact * 2;
protected static int fact3 = fact * 3;
protected static int fact4 = fact * 4;
protected static int fact5 = fact * 5;

// Buttons
public static int btnW = 1;
public static int btnH = 1;
public static int btnGap = 1;


// =============================================================== Текст с тенью
protected static void drawShadText(String text, Paint font, int x, int y,
		int color, int shadColor) {

	font.setColor(shadColor);
	g.drawText(text, x + fact, y + fact + font.getTextSize(), font);
	font.setColor(color);
	g.drawText(text, x, y + font.getTextSize(), font);
}


// ================================================== Освободить ресурсы и выйти
public static void exit() {

	g = null;
}


// ======================================================= Инициализация шрифтов
public static void initFont() {

	Log.v("Scr.initFont", "Инициализирую шрифты");

	//Для часов
	fontClk = new Paint();
	fontClk.setAntiAlias(true);
	fontClk.setTextSize(fontClkH);

	//Для строки статуса
	fontStat = new Paint();
	fontStat.setAntiAlias(true);
	fontStat.setTextSize(fontStatH);

	//Для сообщений
	fontMess = new Paint();
	fontMess.setAntiAlias(true);
	fontMess.setTextSize(fontMessH);

	//Для заголовков
	fontTit = new Paint();
	fontTit.setAntiAlias(true);
	fontTit.setTextSize(fontTitH);

	// Определяем ширину полей часов
	StringBuffer temp = new StringBuffer(8);

	timeMessW = 0;
	for (int q = 0; q <= 9; ++q) {
		temp.append(q).append(q).append(':').append(q).append(q);
		if (fontMess.measureText(temp.toString()) > timeMessW) {
			timeMessW = (int) fontMess.measureText(temp.toString());
		}
		temp.delete(0, temp.capacity());
	}
	timeMessOff = (int) fontClk.measureText(" ");

	timeStatW = 0;
	for (int q = 0; q <= 9; ++q) {
		temp.append(q).append(q).append(':').append(q).append(q);
		if (Setting.fClkSec) {
			temp.append(':').append(q).append(q);
		}
		if (fontStat.measureText(temp.toString()) > timeStatW) {
			timeStatW = (int) fontStat.measureText(temp.toString());
		}
		temp.delete(0, temp.capacity());
	}
}


// ======================================================================= rectG
/**
 * Draw vertical gradient rectangle.
 * 
 * @param g
 * @param x
 * @param y
 * @param w
 * @param h
 * @param col1
 * @param col2
 */
public static void rectG(Canvas g, int x, int y, int w, int h, int col1,
		int col2) {

	LinearGradient grad = new LinearGradient(x, y, x, y + h, col1, col2,
			TileMode.REPEAT);
	Paint paint = new Paint();
	paint.setShader(grad);
	g.drawRect(new Rect(x, y, x + w, y + h), paint);
}


//// ===================================================== Задать графическое поле
//public static void setGr(Canvas gr) {
//
//	Draw.g = gr;
//}


//================================================================== calcFactors
private static final int MIN_BTNS_NUM = 5; // Minimum number of buttons that fits narrower screen side
private static final float WH_PROP = 1.3F; // Buttons width/height proportion
private static final float BTN_GAP_PROP = .1F; // Buttons width to gaps width proportion


/**
 * Задать новый размер экрана и рассчитать коэффициенты, зависимые от него.
 * 
 */
public static void sizeChanged(int newW, int newH) {

	Log.v("Draw.sizeChanged", "Size changed from " + Draw.dispW + " x "
			+ Draw.dispH + " to " + newW + " x " + newH);

	if (Draw.dispW < newW || Draw.dispH < newH) {
		Bitmap oldBmp = Draw.bmp;
		Draw.bmp = Bitmap.createBitmap(newW, newH, Bitmap.Config.ARGB_8888);
		Draw.g = new Canvas(Draw.bmp);
		g.drawColor(Color.rgb(0xff, 0xff, 0xff));
		if (oldBmp != null) {
			g.drawBitmap(oldBmp, 0, 0, null);
		}
	}

	Draw.dispW = newW;
	Draw.dispH = newH;

	int minSize = newW < newH ? newW : newH;
	btnW = (int) ((minSize - fact4) / (MIN_BTNS_NUM + (BTN_GAP_PROP * (MIN_BTNS_NUM + 1))));
	btnH = (int) (btnW / WH_PROP);
	btnGap = (int) (btnW * BTN_GAP_PROP);

	Draw.initFont();
}


// ==================================================================== isInside
/**
 * Chacks if the point with coordinates X, Y lies inside the triangle with
 * coordinates boxX, boxY and with dimensions boxW, boxH.
 */
public static boolean isInside(int x, int y, int boxX, int boxY, int boxW,
		int boxH) {

	if (x < boxX || y < boxY || x > (boxX + boxW) || y > (boxY + boxH)) {
		return false;
	} else {
		return true;
	}
}


//================================================================== makeColShad
/**
 * Returns color with a shadow, created from two colors.
 * 
 * @param color
 *          Main color
 * @param shad
 *          Shadow color
 * @return Color with a shadow applied
 */
public static int makeColShad(int color, int shad) {

	return Color.rgb(
			Color.red(color) - Color.red(shad) > 0 ? Color.red(color)
					- Color.red(shad) : 0,
			Color.green(color) - Color.green(shad) > 0 ? Color.green(color)
					- Color.green(shad) : 0,
			Color.blue(color) - Color.blue(shad) > 0 ? Color.blue(color)
					- Color.blue(shad) : 0);
}


}
